<?php
use Workerman\Worker;
use \Workerman\Lib\Timer;
require_once './Workerman/Autoloader.php';
// 初始化一个worker容器，监听1234端口
$worker = new Worker('websocket://120.77.57.178:1234');
// 这里进程数必须设置为1
$worker->count = 1;
// worker进程启动后建立一个内部通讯端口
$worker->onWorkerStart = function($worker)
{
	echo "worker runing";
};
// 新增加一个属性，用来保存token到connection的映射
$worker->tokenConnections = array();
// 当有客户端发来消息时执行的回调函数
$worker->onMessage = function($connection, $data)use($worker)
{
    $data = json_decode($data,true);
    $token = $data['token'];
   
    // 判断当前客户端是否已经验证,既是否设置了token
  
       // 没验证的话把第一个包当做token（这里为了方便演示，没做真正的验证）
       $connection->token = $token;
	 
       /* 保存token到connection的映射，这样可以方便的通过token查找connection，
        * 实现针对特定token推送数据
        */

	   $redis = new Redis();  
   	   $redis->connect('r-wz91703acc30a984.redis.rds.aliyuncs.com', 6379);  
       $redis->auth('Dida168168'); 
 
      if($redis->get('token') == $token){
        $result = "{code:20004,message:unlogin}";
        $result['code']='500';
        $result['message']='unlogin';
	$resq = json_encode($result,true);
	$ret = sendMessageByUid($token,$resq);
       } 
      

       $userPhone = checkIfUserLogin($token);
		
       $worker->tokenConnections[$connection->token] = $connection;
       // 获取$token,先认证token是否已经登录，如果没有登录，返回未登录；查询是否有这个订单，然过没有，返回没有这个订单；然后，若通过，通过手机号码取出司机的位置，并且返回；
	print_r($userPhone);      
      if(strlen($userPhone) == 11)
      {
       // 每2秒执行一次
       $time_interval = 2;
	$timer_id  = Timer::add($time_interval, function()use($token,$userPhone)
	{      
        $redis = new Redis();  
   	    $redis->connect('r-wz91703acc30a984.redis.rds.aliyuncs.com', 6379);  
        $redis->auth('Dida168168'); 
 
         
		$Order = $redis->hgetall("usecar:".$userPhone);
	   
		print_r($Order);
		if(!empty($Order)){	
			$redisResult = $redis->hgetall("startcar:".$Order['driverPhone']);
			$location = $redisResult['driverPosition'];
			$destinationPosition = $Order['destinationPosition'];
			$OrderStatus = $Order['isAccept'];
                //把经纬度划分为四个点
			$usercarLoaction = explode(",",$Order['fromPosition']);
			$driverLoaction = explode(",",$location);
                $distance = getDistance($usercarLoaction[1], $usercarLoaction[0], $driverLoaction[1], $driverLoaction[0])/1000	;
			// 通过workerman，向token的页面推送数据
			$result['code']=200;
			$result['message']='ok';
			$result['data']['position']=$location;
			$result['data']['desPosition']=$destinationPosition;
			$result['data']['distance']=$distance;
			$result['data']['status']=$OrderStatus;
			$resq = json_encode($result,true);
			$ret = sendMessageByUid($token, $resq);
		}else{
			$result['code']=200;
			$result['message']='ok';
			$result['data']['status']='-1';
			$resq = json_encode($result,true);
			$ret = sendMessageByUid($token, $resq);
        }
	});

	
    }else{
        $redis->set('token', $token); //标注这个token非法
	$result = "{code:20004,message:unlogin}";
        $result['code']='500';
        $result['message']='unlogin';
	$resq = json_encode($result,true);
	$ret = sendMessageByUid($token,$resq);
    }
};

// 当有客户端连接断开时
$worker->onClose = function($connection)use($worker)
{
    global $worker;
    if(isset($connection->token))
    {
        // 连接断开时删除映射
        unset($worker->tokenConnections[$connection->token]);
	echo "$connection->token断开连接";
    }
};

// 向所有验证的用户推送数据
function broadcast($message)
{
   global $worker;
   foreach($worker->tokenConnections as $connection)
   {
        $connection->send($message);
   }
}

// 针对token推送数据
function sendMessageByUid($token, $message)
{
    global $worker;
    if(isset($worker->tokenConnections[$token]))
    {
        $connection = $worker->tokenConnections[$token];
        $connection->send($message);
        return true;
    }
    return false;
}

/**
*  @desc 根据两点间的经纬度计算距离
*  @param float $lat 纬度值
*  @param float $lng 经度值
*/
 function getDistance($lat1, $lng1, $lat2, $lng2)
 {
     $earthRadius = 6367000; //approximate radius of earth in meters

     /*
       Convert these degrees to radians
       to work with the formula
     */

     $lat1 = ($lat1 * pi() ) / 180;
     $lng1 = ($lng1 * pi() ) / 180;

     $lat2 = ($lat2 * pi() ) / 180;
     $lng2 = ($lng2 * pi() ) / 180;

     /*
       Using the
       Haversine formula

       http://en.wikipedia.org/wiki/Haversine_formula

       calculate the distance
     */

     $calcLongitude = $lng2 - $lng1;
     $calcLatitude = $lat2 - $lat1;
     $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);  $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
     $calculatedDistance = $earthRadius * $stepTwo;

     return round($calculatedDistance);
 }

function checkIfUserLogin($token){

	$curl = curl_init();

	curl_setopt_array($curl, array(
	  CURLOPT_URL => "https://api.didame.com:8088/api/checkDriverLocation",
	  CURLOPT_RETURNTRANSFER => true,
	  CURLOPT_ENCODING => "",
	  CURLOPT_MAXREDIRS => 10,
	  CURLOPT_TIMEOUT => 30,
	  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	  CURLOPT_CUSTOMREQUEST => "POST",
	  CURLOPT_HTTPHEADER => array(
	    "authorization: Bearer $token",
	  ),
	));

	$response = curl_exec($curl);
	$err = curl_error($curl);

	curl_close($curl);

	if ($err) {
	  //echo "cURL Error #:" . $err;
	  return 0;
	} else {
	  return $response;
	}
}

// 运行所有的worker（其实当前只定义了一个）
Worker::runAll();
